#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <fstream>
#include "util.hpp"
#include <mutex>
#include <unistd.h>
#include "log.hpp"

namespace ns_index {
    struct DocInfo {
        std::string title;    // 文档的标题
        std::string content;  // 文档去标签后的内容
        std::string url;      // 官网文档url
        uint64_t doc_id;      // 文档的id
    };
   
    struct InvertedElem {
        uint64_t doc_id;
        std::string word;
        int weight;
        InvertedElem() :weight(0) 
        {}
    };

    // 倒排拉链
    typedef std::vector<InvertedElem> InvertedList;

    class Index {
    private:
        // 正排索引的数据结构用数组,数组的下标天然是文档的ID
        std::vector<DocInfo> forward_index;  // 正排索引
        // 倒排索引一定是一个关键字和一组InvertedElem对应 [关键字和倒排拉链的映射关系]
        std::unordered_map<std::string, InvertedList> inverted_index;
        // 单例模式
        static Index *instance;
        static std::mutex mtx;
    
        Index() {}
        Index(const Index&) = delete;
        Index& operator=(const Index&) = delete;
    public:
        ~Index()
        {}
        static Index *GetInstance()
        {
            if (nullptr == instance) {
                mtx.lock();
                if (nullptr == instance) {
                    instance = new Index();
                }
                mtx.unlock();
            }
            return instance;
        }
        // 根据doc_id找到文档的内容
        DocInfo *GetForwardIndex(uint64_t doc_id)
        {  
            if (doc_id >= forward_index.size()) {
                // std::cerr << "doc_id out range, error!" << std::endl;
                LOG(Debug, "doc_id out range, error!");
                return nullptr;
            }
            return &forward_index[doc_id];
        }

        // 根据关键字string,获取倒排拉链
        InvertedList *GetInvertedList(const std::string &word)
        {
            auto iter = inverted_index.find(word);
            if (iter == inverted_index.end()) {
                // std::cerr << word << " have no InvertedList" << std::endl;
                LOG(Debug, "have no InvertedList");
                return nullptr;
            }
            return &(iter->second);
        }

        // 根据去标签,格式化之后的文档,构建正排和倒排索引
        bool BuildIndex(const std::string &input) // 
        {
            std::ifstream in(input, std::ios::in | std::ios::binary);
            if (!in.is_open()) {
                // std::cerr << input << " open error" << std::endl;
                LOG(Fatal, "input error, errno: " + std::to_string(errno) + "errstring: " + strerror(errno));
                return false;
            }

            std::string line;
            int count = 0;
            while (std::getline(in, line)) {
                DocInfo *doc = BuildForwardIndex(line);
                if (nullptr == doc) {
                    // std::cerr << "build " << line << " error" << std::endl;
                    LOG(Debug, "build " + line + "error");
                    continue;
                }
                BuildInvertedIndex(*doc);
                ++count;
                // if (count % 50 == 0)  std::cout << "已建立文档索引数量： " << count << " ..." << std::endl;
                if (count % 50 == 0)  LOG(Info, "已建立文档索引数量:" + std::to_string(count));
            }
            LOG(Info, "已建立文档索引数量:" + std::to_string(count));
            return true;
        }

    private:
        // 构建正排索引
        DocInfo *BuildForwardIndex(const std::string &line)
        {
            // 1. 解析line,字符串切分
            // line-> 3 string, titile, content, url
            std::vector<std::string> results;
            const std::string sep = "\3";  // 行内分割符
            ns_util::StringUtil::Split(line, &results, sep);

            if (results.size() != 3) {
                return nullptr;
            }
            // 2. 字符串进行填充到DocInfo
            DocInfo doc;
            doc.title = results[0];
            doc.content = results[1];
            doc.url = results[2];
            doc.doc_id = forward_index.size(); 
            // 3. 插入到正排索引的vector
            forward_index.push_back(std::move(doc));  // doc,html的文件内容,右值引用提高效率
            return &forward_index.back();
        }
        // 构建倒排索引
        bool BuildInvertedIndex(const DocInfo &doc)
        {
            // word -> 倒排拉链
            struct word_cnt {
                int title_cnt;
                int content_cnt;
                word_cnt() :title_cnt(0), content_cnt(0) {}
            };
            std::unordered_map<std::string, word_cnt> word_map;  // 用来暂存词频的映射表

            // 对标题进行结巴分词
            std::vector<std::string> title_words;
            ns_util::JiebaUtil::CutString(doc.title, &title_words);
            // 对结巴分词后的标题进行词频统计
            for (auto title : title_words) {
                boost::to_lower(title); // 统一转化为小写
                word_map[title].title_cnt++;
            }

            // 对内容进行结巴分词
            std::vector<std::string> content_words;
            ns_util::JiebaUtil::CutString(doc.content, &content_words);
            // 对结巴分词后的内容进行词频统计
            for (auto content : content_words) {
                boost::to_lower(content);
                word_map[content].content_cnt++;
            }

            const int x = 8;
            const int y = 1;
            for (auto &word_pair : word_map) {
                InvertedElem item;
                item.doc_id = doc.doc_id;
                item.word = word_pair.first;
                item.weight = x * (word_pair.second.title_cnt) + y * (word_pair.second.content_cnt);
                inverted_index[word_pair.first].push_back(std::move(item));
            }
            return true;
        }
    };
    Index* Index::instance = nullptr;
    std::mutex Index::mtx;
}